/**
 * 树形选择器
 * @author xiaoxujs
 */

import { FC, useEffect, useRef, useState } from "react";
import { SelectBox, SelectListLi, SelectListUl } from "./style";
import { ISelectProps } from "../../type/components";
import { getLabelByValue } from "../../assets/data/dicData";

export const SelectTree: FC<{
    selectTreeList: ISelectProps[],
    onChange: (value: ISelectProps) => void // 选中的值
    value?: string // 选中的值
}> = ({
    selectTreeList,
    onChange,
    value
}) => {
        const selectBoxRef = useRef<HTMLDivElement>(null); // 外层盒子的ref
        const [selectUlShow, setselectUlShow] = useState(false);
        useEffect(() => {

            const handleClickOutside = (event: MouseEvent) => {
                if (selectBoxRef.current && selectBoxRef.current.contains(event.target as Node)) {
                    // 判断是否有元素  判断点击的元素是否在当前元素中 如果在就不收起 相反 就收起
                } else {
                    setselectUlShow(false)
                }

            }
            document.addEventListener('click', handleClickOutside)

            return () => {
                document.removeEventListener('click', handleClickOutside)
            }
        }, [])

        const handleClick = () => {
            setselectUlShow(true)
        }
        // 选中
        const handleSelect = (item: ISelectProps) => {
            setselectUlShow(false)
            onChange && onChange(item)
        }


        return (
            <SelectBox ref={selectBoxRef}>
                <div className="input_box">
                    <input
                        type="search"
                        value={value ? getLabelByValue(value, selectTreeList)  : ''}
                        readOnly
                        onClick={() => handleClick()}
                    />
                    <div className="input_right">
                        <span className="iconfont">&#xe616;</span>
                    </div>
                </div>

                <SelectListUl $show={selectUlShow ? 'true' : 'false'}>
                    {
                        selectTreeList.map((item) => <SelectListLi onClick={() => handleSelect(item)}>
                            {item.label}
                        </SelectListLi>)
                    }

                </SelectListUl>
            </SelectBox>

        )

    }
export default SelectTree;
